package com.sg.zhui.visitor.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.canyinghao.canrefresh.classic.ClassicRefreshView;
import com.core.lib.widget.BufferProgressDialog;
import com.sg.zhui.visitor.R;
import com.sg.zhui.visitor.adapter.ApplyForRecordAdapter;
import com.sg.zhui.visitor.bean.ApplyListBean;
import com.sg.zhui.visitor.config.PreferencesHelper;
import com.sg.zhui.visitor.http.AsyncRequest;
import com.sg.zhui.visitor.http.BaseStringCallback_Host;
import com.sg.zhui.visitor.http.BaseStringCallback_Visit;
import com.sg.zhui.visitor.http.MyHttpConstants;
import com.sg.zhui.visitor.http.Setting;
import com.sg.zhui.visitor.utils.DialogUtil_VIsitor;
import com.sg.zhui.visitor.utils.flyn.Eyes_Visitor;
import com.sg.zhui.visitor.widget.OnRVItemClickListener;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by chenlipeng on 2018/8/22 0022
 * describe:  申请和授权记录
 */
public class ApplyForAndAccreditRecordActivity extends AppCompatActivity implements OnRVItemClickListener, AsyncRequest, CanRefreshLayout.OnLoadMoreListener, CanRefreshLayout.OnRefreshListener {
    private String token = "";

    private CanRefreshLayout mRefresh;
    private RecyclerView can_content_view;
    private RelativeLayout mRl_empty;

    private String pageSize = "10";
    private int pageNo = 1;
    private ClassicRefreshView can_refresh_header;
    private ClassicRefreshView can_refresh_footer;
    private ApplyForRecordAdapter applyForRecordAdapter;
    private Boolean isVisitor = true;
    private Dialog mBaseDialog;

    private int GET_ACCESS_DOOR_BY_UINTID = 1;
    private BufferProgressDialog mProfressDialog;

    List<ApplyListBean> baseList = new ArrayList<>();//数据源

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.apply_for_record_activity);
//        ButterKnife.bind(this);

        Eyes_Visitor.setStatusBarColor(ApplyForAndAccreditRecordActivity.this, Color.parseColor("#70A0EC"));  //translucent 透明的


        PreferencesHelper preferencesHelper = new PreferencesHelper(ApplyForAndAccreditRecordActivity.this);
        token = preferencesHelper.getToken();
//        token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJqd3QiLCJpYXQiOjE1NDM0OTA5MTksInN1YiI6IntcImNhcmROb1wiOlwiNDcwOTg4NTQ5XCIsXCJkZXZpY2VJZFwiOlwiYzVhMzgxZmY2MWNhYjQ2MjJhNjI4MDlhMTYxZGRmMDFcIixcIm5pY2tOYW1lXCI6XCLpk4HnvLhcIixcInJvbGVUeXBlXCI6XCJ2aXNpdG9yXCIsXCJzaWRcIjpcIjU3OGM4NTUzNzFhMjQ3MDNhNjIwMWY3YjAxODcyNDA2XCIsXCJ1c2VyTmFtZVwiOlwiMTgyMTAxODI0NjJcIixcInVzZXJUZWxcIjpcIjE4MjEwMTgyNDYyXCIsXCJ1c2VyVHlwZVwiOlwibW9iaWxlXCJ9IiwiZXhwIjoxNTQzOTIyOTE5fQ.ajcqTPLkFG7Vy1zaliCkidTihjkWhlGy2WeqLXREuxM";

        bindViews();
    }


    private void bindViews() {
        LinearLayout topbarLeftLinearLayout = (LinearLayout) findViewById(R.id.topbarLeftLinearLayout);
        topbarLeftLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mRefresh = (CanRefreshLayout) findViewById(R.id.refresh);
        can_content_view = (RecyclerView) findViewById(R.id.can_content_view);

        can_refresh_header = (ClassicRefreshView) findViewById(R.id.can_refresh_header);
        can_refresh_footer = (ClassicRefreshView) findViewById(R.id.can_refresh_footer);

        mRl_empty = (RelativeLayout) findViewById(R.id.rl_empty);

        can_content_view.setLayoutManager(new LinearLayoutManager(ApplyForAndAccreditRecordActivity.this));
        applyForRecordAdapter = new ApplyForRecordAdapter(can_content_view, isVisitor);
        can_content_view.setAdapter(applyForRecordAdapter);

        mRefresh.setOnLoadMoreListener(this);
        mRefresh.setOnRefreshListener(this);
        mRefresh.setMaxFooterHeight(dp2px(ApplyForAndAccreditRecordActivity.this, 150));
        mRefresh.setStyle(0, 0);
        can_refresh_header.setPullStr("下拉刷新");
        can_refresh_header.setReleaseStr("松开刷新");
        can_refresh_header.setRefreshingStr("加载中");
        can_refresh_header.setCompleteStr("");

        ImageView ivArrow = can_refresh_header.getIvArrow();
        ivArrow.setBackgroundResource(R.drawable.classic_pull_arrow_visitor);

        can_refresh_footer.setPullStr("上拉加载更多");
        can_refresh_footer.setReleaseStr("松开刷新");
        can_refresh_footer.setRefreshingStr("加载中");
        can_refresh_footer.setCompleteStr("");

        ImageView ivArrowFooter = can_refresh_footer.getIvArrow();
        ivArrowFooter.setBackgroundResource(R.drawable.classic_pull_arrow_visitor);

        getAccessDoorByUintId();
    }


    @Override
    public void onLoadMore() {
//        pageNo++;
//        getAccessDoorByUintId();

        if (baseList.size() >= Integer.parseInt(pageSize) * pageNo) {
            pageNo++;
            getAccessDoorByUintId();
        } else {
            mRefresh.loadMoreComplete();
            Toast.makeText(this, "没有更多数据", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        getAccessDoorByUintId();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        finish();//加true ,带动画
    }

    @Override
    public void onRVItemClick(ViewGroup parent, View itemView, int position) {

    }

    /**
     */
    private void getAccessDoorByUintId() {
//        	请求方式get，不验证token
        String url = Setting.queryVisitorApplyList();

        if (token.equals("")) {
            return;
        }
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("pageNo", pageNo + "");//
        stringStringHashMap.put("pageSize", pageSize);//
        stringStringHashMap.put("applyType", "0");//申请类型 0访客或者员工申请 1 员工授权

        OkHttpUtils
                .post().params(stringStringHashMap)
                .url(url)
                .id(GET_ACCESS_DOOR_BY_UINTID)
                .addHeader("Auth-Token", token)
                .build()
                .execute(new BaseStringCallback_Visit(ApplyForAndAccreditRecordActivity.this, this));
    }

    @Override
    public void RequestComplete(Object object, Object data) {
//        LogUtilBase.LogD("TAG", data.toString());

        if (object.equals(GET_ACCESS_DOOR_BY_UINTID)) {
            String result = (String) data;
//                JSONObject jsonObject = new JSONObject(result);
//                String code = jsonObject.getString("code");
//                JSONObject dataS = (JSONObject) jsonObject.get("data");

            Message msg = mHandler.obtainMessage();
            msg.what = MyHttpConstants.MSG_LOGIN_SUCCESS;
            msg.obj = result;
            mHandler.sendMessage(msg);
//                {
//                    "code" : 1002,
//                        "msg" : "您没有查看授权记录的权限！",
//                        "data" : null
//                }
        }
    }

    @Override
    public void RequestError(Object object, int errorId, final String errorMessage) {

//        LogUtilBase.LogD("TAG", errorMessage);
        if (object.equals(GET_ACCESS_DOOR_BY_UINTID)) {
//            Message msg = mHandler.obtainMessage();
//            msg.what = MyHttpConstants.MSG_LOGIN_FAIL;
//            msg.obj = errorMessage;
//            mHandler.sendMessage(msg);
            ApplyForAndAccreditRecordActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ApplyForAndAccreditRecordActivity.this, errorMessage + "", Toast.LENGTH_SHORT).show();

                    if (null != mRefresh) {
                        mRefresh.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRefresh.loadMoreComplete();
                                mRefresh.refreshComplete();
                            }

                        }, 1000);

                    }
                }
            });
        }
    }

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case MyHttpConstants.MSG_LOGIN_SUCCESS:


                    String result = (String) msg.obj;
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String code = (String) jsonObject.getString("code");
                        String msgmsg = (String) jsonObject.getString("msg");

                        if (code.equals("1002")) {
                            can_content_view.setVisibility(View.GONE);
                            mRl_empty.setVisibility(View.VISIBLE);

                            Toast.makeText(ApplyForAndAccreditRecordActivity.this, msgmsg, Toast.LENGTH_SHORT).show();
                            return;
                        }

//                        List<ApplyListBean> baseList = new ArrayList<>();

                        JSONObject data = (JSONObject) jsonObject.get("data");
                        JSONArray applyList = (JSONArray) data.get("applyList");

                        if (pageNo == 1) {
                            baseList.clear();

                            if (null != applyList && applyList.length() == 0) {
                                can_content_view.setVisibility(View.GONE);
                                mRl_empty.setVisibility(View.VISIBLE);
                                return;
                            }
                        }

                        if (null != applyList && applyList.length() != 0) {
                            for (int i = 0; i < applyList.length(); i++) {

                                JSONObject itemData = (JSONObject) applyList.get(i);

                                ApplyListBean applyListBean = new ApplyListBean();
                                applyListBean.setAccessEnd(itemData.getString("accessEnd"));
                                applyListBean.setAccessStart(itemData.getString("accessStart"));
                                applyListBean.setApplyState(itemData.getString("applyState"));
                                applyListBean.setAuthorizerId(itemData.getString("authorizerId"));
                                applyListBean.setAuthorizerName(itemData.getString("authorizerName"));

                                applyListBean.setCompanyId(itemData.getInt("companyId"));
                                applyListBean.setCompanyName(itemData.getString("companyName"));
                                applyListBean.setCreatedDate(itemData.getString("createdDate"));
                                applyListBean.setDepartmentId(itemData.getInt("departmentId"));
                                applyListBean.setDetpartmentName(itemData.getString("departmentName"));

                                applyListBean.setIntervieweeId(itemData.getString("intervieweeId"));
                                applyListBean.setIntervieweeName(itemData.getString("intervieweeName"));
                                applyListBean.setNoReason(itemData.getString("noReason"));
                                applyListBean.setSid(itemData.getString("sid"));
                                applyListBean.setVehicleNo(itemData.getString("vehicleNo"));

                                applyListBean.setVisitReason(itemData.getString("visitReason"));
                                applyListBean.setVisitorId(itemData.getString("visitorId"));
                                applyListBean.setVisitorName(itemData.getString("visitorName"));
                                applyListBean.setVisitorTel(itemData.getString("visitorTel"));

                                baseList.add(applyListBean);
                            }//for结束

                            if (pageNo == 1) {
                                applyForRecordAdapter.setData(baseList);
                            } else {
                                applyForRecordAdapter.setData(baseList);
                            }

                            can_content_view.setVisibility(View.VISIBLE);
                            mRl_empty.setVisibility(View.GONE);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (null != mRefresh) {
                        mRefresh.postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                mRefresh.loadMoreComplete();
                                mRefresh.refreshComplete();
                            }
                        }, 1000);

                    }
                    break;
                default:
                    break;
            }
        }

    };


    public int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }

    public void showProgressDialog() {
        if (this.mProfressDialog == null) {
            this.mProfressDialog = new BufferProgressDialog(this, false);
        }

    }


    public void hideProgressDialog() {
        if (this.mProfressDialog != null) {
            this.mProfressDialog.destroyProgressDialog();
            this.mProfressDialog = null;
        }
    }

//    public void hideLoadingDialog() {
//        if (mBaseDialog != null && mBaseDialog.isShowing()) {
//            mBaseDialog.dismiss();
//        }
//    }
//
//    public void showLoadingDialog(String msg) {
//        if (msg != null) {
//            if (mBaseDialog != null && mBaseDialog.isShowing()) {
//                mBaseDialog.dismiss();
//                mBaseDialog = null;
//            }
//            mBaseDialog = DialogUtil_VIsitor.showLoading(msg, ApplyForAndAccreditRecordActivity.this);
//        }
//    }
}
